package com.yang.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.regex.Pattern;

public class PublicUtil {
    /**
     * 获得六位验证码
     * @return
     */
    public static String getSixNum() {
        String str = "0123456789";
        StringBuilder sb = new StringBuilder(4);
        for (int i = 0; i < 6; i++) {
            char ch = str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        return sb.toString();
    }

    /**
     * 判断验证码是否已经过了两分钟
     * @param time
     * @return
     */
    public static boolean judgeCodeTime(long time){
        long minute = (System.currentTimeMillis()-time)/(60*1000);
        if(minute>2){
            return false;
        }
        return true;
    }

    /**
     * 把毫秒级时间转成天数
     * @param time
     * @return
     */
    public static String chargeMillisToDay(long time){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);
        Date date = c.getTime();
        return sdf.format(date);
    }

    /**
     * 把日期改为millis
     * @param day
     * @return
     */
    public static long chargeDatToMillis(String day){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        System.out.println("day = "+day);
        long time = 0L;
        try {
            time = simpleDateFormat.parse(day).getTime();
            System.out.println("time = "+time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 计算到期日期
     * @param millis
     * @param day
     * @return
     */
    public static String countDeadline(long millis,int day){
        long oneDay = 86400000L;
        long rentingDay = day * oneDay;
        millis += rentingDay;
        return chargeMillisToDay(millis);
    }

    /**
     * 判断电话号码格式是否正确
     * 格式正确 return true
     * 格式错误 return false
     * @author yang
     * @param mobile
     * @return 格式正确 return true  格式错误 return fals
     */
    public static boolean checkPhone(String mobile) {
        return Pattern.matches("^1[3|4|5|6|7|8|9][0-9]{9}$",mobile);
    }

    /**
     * 判断密码复杂度
     * 数字+字母
     * @param password
     * @return  存在特殊符号、纯字母或纯数字返回 true  \n其他返回 false
     */
    public static boolean checkPassword(String password){
        if(password.length()<8){
            return true;
        }
        String pattern1 = "^(?:(.*)[!@#$%^&*_+=~`<>,/\\;():\"\"''-]+(.*))$";
        String pattern2 = "^(?:\\d+|[a-zA-Z]+)$";
        if(Pattern.matches(pattern1,password)){
            return true;
        }
        return  Pattern.matches(pattern2,password);
    }
}
